package cn.ty.znsz.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

import cn.ty.znsz.common.model.SysMenu;
import net.sourceforge.pinyin4j.PinyinHelper;

public class CommonUtils {
	private static final Logger logger = Logger.getLogger(CommonUtils.class);
	
	/**
	 * 递归获取子节点方法
	 * @param id 父节点id
	 * @param allMenus 所有菜单列表
	 * @return 每个根节点下，所有子菜单列表
	 */
	public static List<SysMenu> getChild(int id,List<SysMenu> allMenus){
	    //子菜单
	    List<SysMenu> childList = new ArrayList<SysMenu>();
	    for (SysMenu sm : allMenus) {
	      // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
	      //相等说明：为该根节点的子节点。
	      if(sm.getParentId()==id){
	        childList.add(sm);
	      }
	    }
	    //递归
	    for (SysMenu sm : childList) {
	    	sm.put("children", getChild(sm.getId(), allMenus));
	    }
	    //如果节点下没有子节点，返回一个空List（递归退出）
	    if(childList.size() == 0){
	      return null;
	    }
	    return childList;
	  }
	
	/**
	 * 后台数据写入HTML全局变量
	 * @param map
	 * @return
	 */
	public static String renderHtmlText(Ret ret){
		String text = "<script src='/assets/layui-v2.2.5/layui.js'></script><script>", httpurl = PropKit.get("httpurl");
		text += "layui.use('layer', function(){var layer=layui.layer;layer.msg('" + ret.getStr("msg") + "', {icon: 2, offset: '10px', time: 2000},"
			 +  " function(){ top.location.href = '" + httpurl + "/login'; });});</script>";
		return text;
	}
	/**
     * 得到中文首字母,例如"专科"得到zk返回
     * @param str 中文字符串
     * @return
     */
    public static String getPinYinHeadChar(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char word = str.charAt(i);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                sb.append(pinyinArray[0].charAt(0));
            } else {
                sb.append(word);
            }
        }
        return sb.toString();
    }
    /**
	 * 信息发布生成网页模板
	 * 
	 * @param title
	 * @param senddeptname
	 * @param content
	 * @return
	 */
	public static String infoHtmlTept(String title, String senddeptname, String content) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(new Date());
		StringBuilder sb = new StringBuilder();
		sb.append("<html>");
		sb.append("<head>");
		sb.append("<title></title>");
		sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
		sb.append("<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">");
		sb.append("<style type=\"text/css\">");
		sb.append("html { overflow-x:hidden; } body{display: block;}");
		sb.append(".zkedu_emoticons { width: 24px !important; }");
		sb.append("p img,div img,p video, div video,p{width: 100% !important;text-indent: 0;}");
		sb.append(
				".m-title{padding: 4px;margin-top: 12px;font-size: 22px;font-weight: 600;text-align: center;line-height: 32px;}");
		sb.append(".m-info{padding: 10px 16px;font-size: 14px;text-align: center;color: #acacac;}");
		sb.append(
				".m-info:after{content: '';display: block;width: 98%;margin: 12px auto 0;border-bottom: 1px solid #16b593;}");
		sb.append(".h-time{margin-right: 20px;}");
		sb.append(".m-detail{padding: 12px;font-size: 16px;line-height: 30px;}");
		sb.append("</style></head>");
		sb.append("<body>");
		sb.append("<div class=\"m-title\">" + title + "</div>");
		sb.append("<div class=\"m-info\"><span class=\"h-time\">" + date + "</span><span>来源：" + senddeptname
				+ "</span></div>");
		sb.append("<div class=\"m-detail\">" + content + "</div>");
		sb.append("</body>");
		sb.append("</html>");
		return sb.toString();
	}
	/**
	 * 正则表达匹配图片路径
	 * 
	 * @param sHtmlText
	 * @return
	 */
	public static List<String> GetHtmlImageUrlList(String sHtmlText) {
		List<String> sUrlList = new ArrayList<String>();
		// 定义正则表达式用来匹配 img 标签
		Pattern p = Pattern.compile(
				"<img\\b[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic|\\+?)\\b)[^>]*>",
				Pattern.CASE_INSENSITIVE);

		// 搜索匹配的字符串
		Matcher m = p.matcher(sHtmlText);

		String quote = null;
		String src = null;
		while (m.find()) {
			quote = m.group(1);
			src = (quote == null || quote.trim().length() == 0) ? m.group(2).split("\\s+")[0] : m.group(2);
			src = src.replaceAll("%3A", ":").replaceAll("%2F", "/");
			if (src.indexOf("emoticons") < 0) // 去除表情包
				sUrlList.add(src);
		}

		return sUrlList;
	}
	/**
	 * @author TF.Du
	 * @date 2017年2月9日15:05:05
	 * @param path
	 * @param content
	 * @return
	 * @Description: TODO 生成HTML文件
	 */
	public static File strToHtml(String fileName, String content, String dir) {
		// 写入文件
		File file = null;
		OutputStreamWriter osw = null;
		try {
			isExistDir(dir);
			file = new File(dir + "/" + fileName);
			file.setWritable(true, false);
			//System.out.print(file);
			if (!file.exists()) {
				file.createNewFile();
			}
			osw = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("utf-8"));
			osw.write(content);
			osw.flush();
			osw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error("------Exception------", e);
		}
		return file;
	}
	/**
	 * 判断多级路径是否存在，不存在就创建
	 * 
	 * @param filePath
	 *            支持带文件名的Path：如：D:\news\2014\12\abc.text，和不带文件名的Path：如：D:\news\
	 *            2014\12
	 */
	public static void isExistDir(String filePath) {
		String paths[] = { "" };
		// 切割路径
		try {
			String tempPath = new File(filePath).getCanonicalPath();// File对象转换为标准路径并进行切割，有两种windows和linux
			paths = tempPath.split("\\\\");// windows
			if (paths.length == 1) {
				paths = tempPath.split("/");
			} // linux
		} catch (IOException e) {
			System.out.println("切割路径错误");
			e.printStackTrace();
		}
		// 判断是否有后缀
		boolean hasType = false;
		if (paths.length > 0) {
			String tempPath = paths[paths.length - 1];
			if (tempPath.length() > 0) {
				if (tempPath.indexOf(".") > 0) {
					hasType = true;
				}
			}
		}
		// 创建文件夹
		String dir = paths[0];
		for (int i = 0; i < paths.length - (hasType ? 2 : 1); i++) {// 注意此处循环的长度，有后缀的就是文件路径，没有则文件夹路径
			try {
				dir = dir + "/" + paths[i + 1];// 采用linux下的标准写法进行拼接，由于windows可以识别这样的路径，所以这里采用警容的写法
				File dirFile = new File(dir);
				if (!dirFile.exists()) {
					dirFile.mkdir();
					System.out.println("成功创建目录：" + dirFile.getCanonicalFile());
				}
			} catch (Exception e) {
				System.err.println("文件夹创建发生异常");
				e.printStackTrace();
			}
		}
	}
	/**
	 * 上传新闻图片
	 */
	public static Ret imgUpload(List<UploadFile> files,String dir) {
		List<Record> list=new ArrayList<Record>();
		for(int i=0;i<files.size();i++){
			Record record=new Record();
			File file=files.get(i).getFile();
			String filename = file.getName();
			if (filename.lastIndexOf('.') != -1) {
				filename = filename.substring(filename.lastIndexOf('.'));
			}
			filename =StrKit.getRandomUUID() + filename;
			file.renameTo(new File(PropKit.get("sharereal")+dir+"/"+filename));
			record.set("url", "/myshare"+dir+"/"+ filename);
			list.add(record);
		}
		return Ret.ok("操作成功").set("data", list).set("errno", 0).set("code", "0");
	}
	/**
	 * 上传新闻视频
	 */
	public static Ret videoUpload(File file,String dir) {		
		String filename = file.getName();
		if (filename.lastIndexOf('.') != -1) {
			filename = filename.substring(filename.lastIndexOf('.'));
		}
		filename =StrKit.getRandomUUID() + filename;
		String str=dir+filename;
		file.renameTo(new File(PropKit.get("sharereal")+str));			
		return Ret.ok("操作成功").set("data", Ret.create().set("url", "/myshare"+str)).set("errno", 0).set("code", "0");
	}
}
